package com.cxyd.modules.job.task.agvTask;

import com.cxyd.modules.api.dto.RcsResultYF;
import com.cxyd.modules.wcs.dto.AgvTrkYfPostDTO;
import com.cxyd.modules.wcs.entity.TrkEntity;
import com.cxyd.modules.wcs.entity.UrlMappingEntity;
import com.cxyd.modules.wcs.service.AgvTrkYfService;
import com.cxyd.modules.wcs.service.TrkService;
import com.cxyd.modules.wcs.service.UrlMappingService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.springframework.web.client.RestTemplate;

import javax.annotation.Resource;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

@Component("yf-task")
@Slf4j
public class YFTask {
    //    创建锁，防止并发情况出现
    private Lock lock = new ReentrantLock();
    //处理宇锋货架任务
    @Resource
    private TrkService trkService;
    @Resource
    private AgvTrkYfService agvTrkYfService;
    @Resource
    private UrlMappingService urlService;
    @Resource
    private RestTemplate restTemplate;

    public void scanTask() {
        lock.lock();
        try {
//            获取属于宇锋的[wcs_trk]搬送任务
            final TrkEntity wcsTrk = trkService.selectByDvcNo("YF_AGV");
            if (wcsTrk == null) {
//                log.info("暂无[YF_AGV]搬送的任务!");
                return;
            }
            agvTrkYfService.yfTrkScan(wcsTrk);
        } catch (Exception e) {
            log.error("扫描[YF_AGV]任务异常，causeBy:{}", e.getMessage());
        } finally {
            lock.unlock();
        }
    }

    public void postTask() {
        lock.lock();
        try {
//            优先获取一下路由信息
            UrlMappingEntity url_yf = urlService.getUrlByNo("YF_POST_URL");
            if (url_yf == null || url_yf.getUrlAdr().isEmpty()) {
                log.info("[YF_POST_URL]未配置!");
                return;
            }
//            获取属于宇锋的[agv_trk_yf]搬送任务
            AgvTrkYfPostDTO agvTrkYF = agvTrkYfService.getPostYfTrk();
            if (agvTrkYF == null) {
//                log.info("暂无[YF_AGV]的搬送任务!");
                return;
            }
            log.info("获取到待下发任务：{}", agvTrkYF);
            RcsResultYF respond = restTemplate.postForObject(url_yf.getUrlAdr(), agvTrkYF, RcsResultYF.class);
            if (respond == null) {
                return;
            }
//            处理已下发搬送任务
            agvTrkYfService.agvTrkHandle(agvTrkYF, respond);
        } catch (Exception e) {
            log.error("下发[YF_AGV]搬送任务异常，causeBy:{}", e.getMessage());
        } finally {
            lock.unlock();
        }
    }
}
